package com.yzdbx.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.yzdbx.utils.DbUtil;
import com.yzdbx.utils.GenUtil;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.*;
import java.sql.Date;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.yzdbx.task.ProductOrderRunnable.GEN_PRODUCT_ORDER_IDS;
import static com.yzdbx.task.SalefOrderRunnable.GEN_ORDER_IDS;
import static com.yzdbx.utils.DbUtil.getMaxId;
import static com.yzdbx.utils.GenUtil.*;

/**
 * @BelongsProject: SERVEVICE-DATA-GEN
 * @BelongsPackage: com.yzdbx.task
 * @Author: lk
 * @CreateTime: 2025-05-14
 * @Description: 成品检验
 * @Version: 1.0
 */
@SuppressWarnings("all")
public class FinishedProductInspectionRunnable implements Exe {


    private Connection connection;


    private static final String serialNoMaxWithCurentDay = "select * from qualityCheckTasksheet where qualitativeTaskNo like concat(?,'%') order by qualitativeTaskNo desc limit 1";

    public FinishedProductInspectionRunnable(Connection connection) {
        this.connection = connection;
    }

    public boolean execute(int count) {
        List<Integer> list = GEN_PRODUCT_ORDER_IDS.get();
        if (CollectionUtil.isEmpty(list)) return Boolean.TRUE;
        Integer orderId = RandomUtil.randomEle(list);

        Map<String, Object> productOrder = DbUtil.getById(connection, "missionInformationSc02", orderId);

        //创建成品检验
        int id = getMaxId(connection, "qualityCheckTasksheet") + 1;

        try {
            PreparedStatement prepareStatement = connection.prepareStatement(serialNoMaxWithCurentDay);
            prepareStatement.setString(1, CUR_DATE.get().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
            List<LinkedHashMap<String, Object>> linkedHashMaps = DbUtil.resultSetToList(prepareStatement.executeQuery());
            Long serialNo = 1L;
            if (CollectionUtil.isNotEmpty(linkedHashMaps)) {
                LinkedHashMap<String, Object> linkedHashMap = linkedHashMaps.get(0);
                String qualitativeTaskNo = linkedHashMap.get("qualitativeTaskNo").toString();
                serialNo = Long.parseLong(qualitativeTaskNo) + 1L;
                return Boolean.TRUE;
            }

            prepareStatement = connection.prepareStatement("insert into qualityCheckTasksheet(id,qualitativeTaskNo,taskStatus,productVarieties,qualityStandards,association1,taskType,plannedCompletion,actualCompletionTime)values (?,?,?,?,?,?,?,?,?)");
            prepareStatement.setInt(1, id);
            prepareStatement.setString(2, serialNo == 1L ? getNoFromTable(connection,"", "qualityCheckTasksheet","id") : serialNo.toString());
            prepareStatement.setString(3, "已完成");
            // 用产品名称查找产品
            String productName = Objects.toString(productOrder.get("productName"), "");
            Map<String, Object> product = DbUtil.getByField(connection, "gy02ProductRepository", "productName", productName);
            String dataTitle1 = product != null ? Objects.toString(product.get("dataTitle1"), "") : "";
            prepareStatement.setString(4, dataTitle1);
            prepareStatement.setString(5, "成品检测");
            prepareStatement.setString(6, productOrder.get("missionStream").toString());
            prepareStatement.setString(7, "成品检");
            prepareStatement.setDate(8, ((Date) productOrder.get("endOfSchedule")));
            prepareStatement.setDate(9, ((Date) productOrder.get("endOfSchedule")));
            prepareStatement.execute();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }

        return Boolean.TRUE;
    }

    public static void main(String[] args) {


        Connection connection = DbUtil.getConnection();

        try {
            PreparedStatement statement = connection.prepareStatement("select * from missionInformationSc02");
            List<LinkedHashMap<String, Object>> rwList = DbUtil.resultSetToList(statement.executeQuery());

            Map<Object, List<LinkedHashMap<String, Object>>> rwGroups = rwList.stream().collect(Collectors.groupingBy(cur -> cur.get("otherOrganiser")));

            LocalDate start = ((Date) rwList.stream().min(Comparator.comparing(o -> (Date) o.get("otherOrganiser"))).stream().toList().get(0).get("otherOrganiser")).toLocalDate();

            LocalDate end = ((Date) rwList.stream().max(Comparator.comparing(o -> (Date) o.get("otherOrganiser"))).stream().toList().get(0).get("otherOrganiser")).toLocalDate();

            while (!start.isAfter(end)) {
                Date s = Date.valueOf(start);
                List<LinkedHashMap<String, Object>> rwListCur = rwGroups.get(s);
                if (CollectionUtil.isEmpty(rwListCur)) continue;
                GEN_PRODUCT_ORDER_IDS.set(rwListCur.stream().map(cur -> (Integer) cur.get("id")).toList());
                CUR_DATE.set(start);
                new FinishedProductInspectionRunnable(connection).execute(0);
                start = start.plusDays(1);
            }

            connection.commit();

        } catch (Exception ex) {
            try {
                connection.rollback();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } finally {
            DbUtil.closeConnection(connection);
        }
    }

}
